<template>
  <form class="row">
    <div class="col">
      <label class="form-label" v-if="label">{{ label }}</label>
      <input :type="type" v-model="value" class="form-control" :class="{ 'is-invalid': message }" />
      <div class="invalid-feedback" v-show="message">{{ message }}</div>
    </div>
  </form>
</template>
<script lang="ts">
import { defineComponent, ref, watch } from "vue";

export default defineComponent({
  props: {
    label: String,
    type: { type: String, default: "text" },
    reg: { type: Object, default: null },
    invalidMes: { type: String, default: "请输入正确的信息" },
    requiredMes: { type: String, default: "请填写该字段" },
  },
  setup(props) {
    const value = ref("");
    const message = ref("");
    watch(value, () => {
      doValid();
    });
    function doValid() {
      if (value.value === "") {
        message.value = props.requiredMes;
      } else if (props.reg) {
        message.value = props.reg.test(value.value) ? "" : props.invalidMes;
      } else {
        message.value = "";
      }
      return message.value === "" ? value.value : false;
    }
    return {
      value,
      message,
      doValid,
    };
  },
});
</script>
